package com.hotai.service.impl;

import cn.hutool.core.lang.func.Func1;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.*;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hotai.comment.dtos.PageResponseResult;
import com.hotai.comment.dtos.ResponseResult;
import com.hotai.comment.enums.ApkUtil;
import com.hotai.comment.enums.AppHttpCodeEnum;
import com.hotai.comment.enums.AppJwtUtil;
import com.hotai.comment.fastDFS.AliyunConfig;
import com.hotai.comment.fastDFS.MultipartFileToFileUtil;
import com.hotai.comment.filter.TokenInterceptor;
import com.hotai.comment.md5.MD5Utils;
import com.hotai.comment.pojo.*;
import com.hotai.mapper.*;
import com.hotai.service.CoursewareService;
import com.hotai.vo.account.*;
import com.hotai.vo.ban.BanPage;
import com.hotai.vo.ban.BanPian;
import com.hotai.vo.bao.Baogao;
import com.hotai.vo.bao.CoursewareBaoStudentList;
import com.hotai.vo.courseware.*;
import com.hotai.vo.sho.*;
import com.hotai.vo.tupian.Pian;
import io.jsonwebtoken.Claims;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.xmlpull.v1.XmlPullParser;

import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.sql.Wrapper;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


@Service
public class CoursewareServiecImpl extends ServiceImpl<CoursewareMapper, Courseware> implements CoursewareService {
    @Autowired
    private CoursewareMapper coursewareMapper;


    @Autowired
    UserStudentMapper userStudentMapper;

    @Autowired
    UserTeacherMapper userTeacherMapper;

    @Autowired
    EquipmentMapper equipmentMapper;

    @Autowired
    CorsewareEquipmentMapper corsewareEquipmentMapper;

    @Autowired
    private CoursewareTopMapper coursewareTopMapper;


    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    private static final String[] IMAGE_TYP = new String[]{".apk"};


    @Autowired
    private OSSClient ossClient;

    @Autowired
    private AliyunConfig aliyunConfig;

    @Autowired
    private SheGenMapper sheGenMapper;

    @Autowired
    private CoursewareStudentMapper coursewareStudentMapper;

    @Override
    public ResponseResult PageList(CoursewareList query) {
        //参数为空
        if (query == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        query.checkParam();
        PageHelper.startPage(query.getPage(), 20);
        //前端穿过来字符串,分割
        String clas = query.getClas();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //判断是不是为空
        if (StringUtils.isNotBlank(clas)) {
            //，分割 存到list 数组
            List<String> searchParityList = Arrays.asList(clas.split(","));
            //存到map集合
            paramMap.put("clas", searchParityList);
        }
        query.setParamMap(paramMap);
        ArrayList<CoursewareLIstZhan> detaile = coursewareMapper.CoursewareList(query);
        ArrayList<CoursewareLIstZhan> detaileShi = coursewareMapper.CoursewareShi();
        for (CoursewareLIstZhan zhan : detaile) {
            for (CoursewareLIstZhan coursewareLIstZhan : detaileShi) {
                if (zhan.getId().equals(coursewareLIstZhan.getId())) {
                    zhan.setShi(coursewareLIstZhan.getShi());
                    break;
                }
            }
        }
        PageInfo<CoursewareLIstZhan> pageInfo = new PageInfo<>(detaile);
        PageResponseResult responseResult = new PageResponseResult(query.getPage(), pageInfo.getSize(), (int) pageInfo.getTotal());
        responseResult.setData(pageInfo.getList());
        return responseResult;
    }

    @Override
    public ResponseResult Waredetail(CoursewaredetaileList queryware) {
        //参数为空
        if (queryware == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        queryware.setPage(1);
        queryware.setSize(20);
        if (queryware.getXueid() == null) {
            queryware.setXueid(1);
        }
        queryware.setPage((queryware.getPage() - 1) * queryware.getSize());
        if (queryware.getXueid() == 1) {
            ArrayList<Coursewaredetaile> detaile = coursewareMapper.detaile(queryware);
            Collections.sort(detaile, new Comparator<Coursewaredetaile>() {
                final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                @Override
                public int compare(Coursewaredetaile o1, Coursewaredetaile o2) {
                    return (o2.getXueDate().toString()).compareTo(o1.getXueDate().toString());
                }
            });
            PageResponseResult responseResult = new PageResponseResult(queryware.getPage() + 1, queryware.getSize(), detaile.size());
            responseResult.setData(detaile);
            return responseResult;
        } else if (queryware.getXueid() == 2) {
            ArrayList<CoursewaredetaileShe> detaile = coursewareMapper.detaileshe(queryware);
            PageResponseResult responseResult = new PageResponseResult(queryware.getPage() + 1, queryware.getSize(), detaile.size());
            responseResult.setData(detaile);
            return responseResult;
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, AppHttpCodeEnum.SERVER_ERROR.getErrorMessage());
    }

    @Override
    public ResponseResult CourseJia(Coursewarejia coursewarejia) {

        if (coursewarejia.getStatus() == 1) {
            coursewareMapper.xiajia(coursewarejia);
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        } else if (coursewarejia.getStatus() == 2) {
            coursewareMapper.shangjia(coursewarejia);
            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, AppHttpCodeEnum.SERVER_ERROR.getErrorMessage());
    }


    @Override
    public ResponseResult deleteId(Integer id) {
        Courseware courseware = coursewareMapper.selectById(id);
        if (courseware.getStatus() != 1) {
            coursewareMapper.delt(id);
            coursewareStudentMapper.deleteId(id);

            return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_ERROR, AppHttpCodeEnum.DELETE_ERROR.getErrorMessage());
    }


    @Override
    public ResponseResult Savedetail(CoursewareSave queryware) {
//        if (queryware.getImg()==null||queryware.getWen()==null||queryware.getStatus()==null){
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, AppHttpCodeEnum.PARAM_REQUIRE.getErrorMessage());
//        }
        if (queryware.getStatus() == null) {
            queryware.setStatus(2);
        }
        if (queryware.getFname().equals("数学几何")) {
            queryware.setSubject("数学");
        }
        if (queryware.getImg() == null) {
            queryware.setImg("https://sheb.oss-cn-beijing.aliyuncs.com/kejian/1658219429835.jpg");
        }
        Courseware courseware = new Courseware();
        if (queryware.getId() == null) {
            courseware.setCreateDate(new Date());
            courseware.setDeid(1);
//            courseware.setTname(queryware.getTname());
//            courseware.setShDate(courseware.getWen().);
            BeanUtils.copyProperties(queryware, courseware);
            coursewareMapper.insert(courseware);
        } else {
            BeanUtils.copyProperties(queryware, courseware);
            coursewareMapper.updateById(courseware);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult CourseFinbyid(Integer id) {
        CoursewareSave coursewareSave = new CoursewareSave();
        CoursewareSaveFindBy coursewareSaveFindBy = new CoursewareSaveFindBy();
        try {
            Courseware courseware = coursewareMapper.selectById(id);
            ArrayList<Pian> pians = new ArrayList<>();
            Pian pian = new Pian();
            if (!courseware.getWename().equals("")) {
                pian.setName(courseware.getWename() + ".apk");
                pian.setUrl(courseware.getWen());
//                pian.setCapacity(courseware.getCapacity());
//                pian.setTime(courseware);
                pians.add(pian);
                coursewareSave.setWenn(pians);
                BeanUtils.copyProperties(courseware, coursewareSave);
                return ResponseResult.success(coursewareSave);
            } else {
                BeanUtils.copyProperties(courseware, coursewareSaveFindBy);
                return ResponseResult.success(coursewareSaveFindBy);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, AppHttpCodeEnum.SERVER_ERROR.getErrorMessage());
    }

    @Override
    public ResponseResult guanShoPage(GuanSho guanSho) {
        //参数为空
        if (guanSho == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        guanSho.checkParam();

//        guanSho.setPage((guanSho.getPage() - 1) * guanSho.getSize());
//        PageHelper.startPage(guanSho.getPage(),guanSho.getSize());
        ArrayList<GuanShoList> detaile = coursewareMapper.GuanShoList(guanSho);
//        Collections.sort(detaile, new Comparator<GuanShoList>(){
//            final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            @Override
//            public int compare(GuanShoList o1, GuanShoList o2) {
//                return (o1.getCreateDate().toString()).compareTo(o2.getCreateDate().toString());
//            }
//        });
        PageResponseResult responseResult = new PageResponseResult(guanSho.getPage(), 5, 5);
        responseResult.setData(detaile);
        return responseResult;

    }


    @Override
    public ResponseResult StuShoPage(XueSho xueSho) {
        //参数为空
        if (xueSho == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //检查参数
        xueSho.checkParam();
        if (xueSho.getFname() == null || xueSho.getFname().equals("")) {
            xueSho.setFname("理化生实验");
        }
        if (xueSho.getFname().equals("理化生实验")) {
            if (xueSho.getSubject() == null || xueSho.getFname().equals("")) {
                xueSho.setSubject("物理");
            }
        }
        if (xueSho.getFname().equals("校园安全")) {
            if (xueSho.getSubject() == null || xueSho.getFname().equals("")) {
                xueSho.setSubject("地震逃生");
            }
        }
        if (xueSho.getFname().equals("人文地理")) {
            if (xueSho.getSubject() == null || xueSho.getFname().equals("")) {
                xueSho.setSubject("大美华夏");
            }
        }

//        xueSho.setPage((xueSho.getPage() - 1) * xueSho.getSize());
        PageHelper.startPage(xueSho.getPage(), 6);

        //设备
        Equipment equipment = equipmentMapper.selectOne(Wrappers.<Equipment>lambdaQuery().eq(Equipment::getXid, xueSho.getXid()));

        //安装课件
        List<CoursewareEquipment> coursewareEquipments = null;
        if (equipment != null) {
            coursewareEquipments = corsewareEquipmentMapper.selectList(Wrappers.<CoursewareEquipment>lambdaQuery().eq(CoursewareEquipment::getEid, equipment.getId()));
        } else {
            return ResponseResult.errorResult(591, "未能找此设备信息");
        }

        ArrayList<XueShoLIst> detaile = coursewareMapper.StuSho(xueSho);
        for (XueShoLIst xueShoLIst : detaile) {
            ArrayList<String> strings = new ArrayList<>();
            String[] split = xueShoLIst.getPattern().split(",");
            for (String s : split) {
                strings.add(s);
            }
            if (coursewareEquipments != null && coursewareEquipments.size() > 0) {
                for (CoursewareEquipment coursewareEquipment : coursewareEquipments) {
                    if (coursewareEquipment.getCid().equals(xueShoLIst.getId())) {
                        xueShoLIst.setStatus(1);
                        break;
                    } else {
                        xueShoLIst.setStatus(2);
                    }
                }
            } else {
                xueShoLIst.setStatus(2);
            }
            xueShoLIst.setPatterns(strings);
        }
        PageInfo<XueShoLIst> pageInfo = new PageInfo<>(detaile);
        PageResponseResult responseResult = new PageResponseResult(xueSho.getPage(), pageInfo.getSize(), (int) pageInfo.getTotal());
        responseResult.setData(pageInfo.getList());
        return responseResult;
    }

    @Override
    public ResponseResult Stushi(CoursewaredetaileList queryware) {
        //参数为空
        if (queryware == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查参数
        queryware.checkParam();
        queryware.setPage((queryware.getPage() - 1) * queryware.getSize());
        ArrayList<Xueshi> detaile = coursewareMapper.StuShi(queryware);
        PageResponseResult responseResult = new PageResponseResult(queryware.getPage() + 1, queryware.getSize(), detaile.size());
        responseResult.setData(detaile);
        return responseResult;
    }

    @Override
    public ResponseResult guanShoShangPage() {
//        Date date = new Date();

        Integer huo = userStudentMapper.huo();


        Integer zeng = userStudentMapper.userzong();


        List<UserStudent> lei = userStudentMapper.selectList(Wrappers.<UserStudent>lambdaQuery().eq(UserStudent::getDeid, 1));
        List<UserTeacher> lei2 = userTeacherMapper.selectList(Wrappers.<UserTeacher>lambdaQuery().eq(UserTeacher::getDeid, 1));

        Integer zengYuan = coursewareMapper.zengYuan();

        List<Courseware> leiyuan = coursewareMapper.selectList(Wrappers.<Courseware>lambdaQuery().eq(Courseware::getDeid, 1));

        List<Equipment> leishe = equipmentMapper.selectList(Wrappers.<Equipment>lambdaQuery().eq(Equipment::getDeid, 1));

        Integer leishi = coursewareMapper.Leishi();
        GuanShoShang guanShoShang = new GuanShoShang();
        guanShoShang.setHuo(huo);
        guanShoShang.setZeng(zeng);
        guanShoShang.setLei(lei.size() + lei2.size());
        guanShoShang.setZengYuan(zengYuan);
        guanShoShang.setLeiyuan(leiyuan.size());
        guanShoShang.setLeishe(leishe.size());
        guanShoShang.setLeishi(leishi);
        return ResponseResult.okResult(guanShoShang);
    }

    @Override
    public ResponseResult deleteIAll(String ide) {
        String[] split = ide.split(",");

        for (String id : split) {
            Courseware courseware = coursewareMapper.selectById(Integer.parseInt(id));
            if (courseware.getStatus() != 1) {
                try {
                    coursewareMapper.delt(Integer.parseInt(id));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult ShangJia(String ide) {
        String[] split = ide.split(",");
        Coursewarejia coursewarejia = new Coursewarejia();
        for (String id : split) {
            coursewarejia.setId(Integer.parseInt(id));
            coursewareMapper.shangjia(coursewarejia);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult XiaJia(String ide) {
        String[] split = ide.split(",");
        Coursewarejia coursewarejia = new Coursewarejia();
        for (String id : split) {
            coursewarejia.setId(Integer.parseInt(id));
            coursewareMapper.xiajia(coursewarejia);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }


    @Override
    public ResponseResult deleteIdShe(Integer cid, Integer eid) {
        if (cid == null || eid == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }
        try {
            coursewareMapper.deleteSheId(cid, eid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }

    @Override
    public ResponseResult xiaZai(Integer id) {
        return null;
    }

    @Override
    public ResponseResult StushiDelete(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }
        coursewareMapper.StushiDelete(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.PQCG, AppHttpCodeEnum.PQCG.getErrorMessage());
    }

    @Autowired
    private CoursewareBaoStudentMapper coursewareBaoStudentMapper;


    @Override
    public ResponseResult Bao(Integer id) {
        CoursewareStudent coursewareStudent = coursewareStudentMapper.selectById(id);
        if (coursewareStudent == null) {
            return ResponseResult.errorResult(576, "有没有次记录");
        }
        Baogao baogao = coursewareMapper.baogao(id);
        //较平均  得分
        Integer zongfen = coursewareMapper.fenshu(baogao.getCid());
        //较平均  得分

        if (zongfen != null &&zongfen>0) {
            baogao.setMeansocre((baogao.getScore() - zongfen) * 100 / zongfen);
        }else {
            baogao.setMeansocre(0);
        }
        //平均时长
        Integer pinshi = coursewareMapper.pinshi(baogao.getCid(), baogao.getSid());
        baogao.setMeantime(pinshi);
        //实验所有人的平均用时
        Integer suoshi = coursewareMapper.soushi(baogao.getCid());
        if (suoshi!=null&&suoshi>0){
            baogao.setLastmeantime((pinshi - suoshi) * 100 / suoshi);
        }else {
            baogao.setLastmeantime(0);
        }
        //上次实验用时
        Integer hshi = coursewareMapper.shijian(baogao.getXueDate(), baogao.getCid(), baogao.getSid());
        if (hshi != null && hshi > 0) {
            baogao.setLastime((int) (baogao.getShi() - hshi) * 100 / hshi);
        } else {
            baogao.setLastime(0);
        }

        //完成步数
        Integer zong = coursewareMapper.accomplish(id);
        baogao.setAccomplish(zong);
        //总步数
        List<CoursewareBaoStudent> coursewareBaoStudents = coursewareBaoStudentMapper.selectList(Wrappers.<CoursewareBaoStudent>lambdaQuery().eq(CoursewareBaoStudent::getEsid, baogao.getId()));

         if (coursewareStudent.getPattern()==1){
             if (coursewareBaoStudents==null||coursewareBaoStudents.size()<=0){
                 baogao.setUp(1);
             }
         }
         if (coursewareStudent.getPattern()==2){
             baogao.setUp(coursewareBaoStudents.size());
         }
        //超出的数量
        Integer beyond = coursewareMapper.beyond(baogao.getScore(), baogao.getCid());
        //总数量
        Integer zongdu = coursewareMapper.zongshu(baogao.getCid());
        //超出% 同学
      if (zongdu!=null&&zongdu>0){
          baogao.setExceed(beyond * 100 / zongdu);
      }else {
          baogao.setExceed(0);
      }
        return ResponseResult.okResult(baogao);
    }


    private String suiji() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 2; i++) {
            result += random.nextInt(10);
        }

        return result;
    }


    @Override
    public ResponseResult pin(Integer sid, Integer cid) {
        Baogao baogao = coursewareMapper.pin(sid, cid);
        return ResponseResult.okResult(baogao);
    }

    @Override
    public ResponseResult bu(Integer id) {
        ArrayList<CoursewareBaoStudentList> coursewareBaoStudents = coursewareMapper.bu(id);
        //平均值
//       ArrayList<CoursewareBaoStudentList> BaoStudentList = coursewareMapper.buPin(coursewareBaoStudents.get(0).getCid(),coursewareBaoStudents.get(0).getSid());
//        //赋值
//        for (CoursewareBaoStudentList baoStudent : coursewareBaoStudents) {
//            for (CoursewareBaoStudentList studentList : BaoStudentList) {
//                if (baoStudent.getBu()==studentList.getBu()){
//                        baoStudent.setPinshi(studentList.getPinshi());
//                }
//            }
//        }
        return ResponseResult.okResult(coursewareBaoStudents);
    }

    @Override
    public ResponseResult Benrenewal(MultipartFile file) {

        // TODO 图片校验
        boolean isLegal = true;
        String type = ".apk";
        if (!StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
            isLegal = false;
        }


        ResponseResult picUploadResult = new ResponseResult();
        // 格式错误, 返回与前端约定的error
        if (!isLegal) {
            return picUploadResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR, AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR.getErrorMessage());
        }

        // 2. 准备上传API的参数
        String fileName = file.getOriginalFilename();
        String filePath = this.getFilerenewalPath(fileName);

        // 3. 上传至阿里OSS
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            picUploadResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, AppHttpCodeEnum.SERVER_ERROR.getErrorMessage());
            return picUploadResult;
        }

        // 上传成功
        picUploadResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        // 文件名(即直接访问的完整路径)
//        String[] split = fileName.split(".apk");

        //apk文件
        File file1 = null;
        BanPian ban = new BanPian();
        ban.setImg(aliyunConfig.getUrlPrefix() + filePath);
        ban.setCapacity((int) (file.getSize() / 1048576));
        ban.setCreateDate(new Date());
        try {
            file1 = multipartFileToFile(file);
            //apk版本信息
            String[] apkInfo = null;
            try {
                apkInfo = ApkUtil.getApkInfo(file1.getPath());
            } catch (Exception e) {
                e.printStackTrace();
            }
            int i = 0;
            for (String s : apkInfo) {
                if (i == 0) {
                    ban.setIname(s);
                }
                if (i == 2) {
                    ban.setVersionName(s);
                }
                i++;
            }
            try {
                ban.setMd(MD5Utils.getMD5(file1));
                MultipartFileToFileUtil.deleteTempFile(file1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        picUploadResult.ok(ban);
        return picUploadResult;
    }


    @Override
    public ResponseResult StuTop(String fname, String xid) {
        if (fname == null || fname.equals("")) {
            fname = "理化生实验";
        }

        //设备
        Equipment equipment = equipmentMapper.selectOne(Wrappers.<Equipment>lambdaQuery().eq(Equipment::getXid, xid));

        //安装课件
        List<CoursewareEquipment> coursewareEquipments = null;
        if (equipment != null) {
            coursewareEquipments = corsewareEquipmentMapper.selectList(Wrappers.<CoursewareEquipment>lambdaQuery().eq(CoursewareEquipment::getEid, equipment.getId()));
        } else {
            return ResponseResult.errorResult(591, "未能找此设备信息");
        }


        ArrayList<ShoTop> shoTops = coursewareMapper.shoTOP(fname);
        for (ShoTop shoTop : shoTops) {
            if (shoTop.getTop()==null){
                shoTop.setTop(0);
            }
            String[] split = shoTop.getPattern().split(",");
            shoTop.setPatterns(split);
            if (coursewareEquipments != null && coursewareEquipments.size() > 0) {
                for (CoursewareEquipment coursewareEquipment : coursewareEquipments) {
                    if (shoTop.getId().equals(coursewareEquipment.getCid())) {
                        shoTop.setStatus(1);
                        break;
                    } else {
                        shoTop.setStatus(2);
                    }
                }
            } else {
                shoTop.setStatus(2);
            }
        }
        return ResponseResult.okResult(shoTops);
    }


    private UserStudent userId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Claims claimsBody = AppJwtUtil.getClaimsFromToken(token);//解析token
        UserStudent userStudent = userStudentMapper.selectById(claimsBody.getId());
        if (userStudent != null) {
            return userStudent;
        }
        return null;
    }

    @Override
    public ResponseResult WareTop(Integer id, String xid, HttpServletRequest request) {
        if (id == null || xid == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }
        UserStudent userStudent = userId(request);
        if (userStudent.getStatus() == 2) {
            return ResponseResult.errorResult(506, "该账号被限制");
        }
        Equipment equipment = equipmentMapper.selectOne(Wrappers.<Equipment>lambdaQuery().eq(Equipment::getXid, xid));
        if (equipment.getStatus() == 2) {
            return ResponseResult.errorResult(590, "该设备已被限制");
        }
        Courseware courseware = coursewareMapper.selectById(id);
        if (courseware == null) {
            return ResponseResult.errorResult(566, "此课件不存在");
        }
        CoursewareTop coursewareTop1 = coursewareMapper.CourseTop(id);
        if (coursewareTop1 == null) {
            CoursewareTop coursewareTop = new CoursewareTop();
            coursewareTop.setCousewareId(id);
            coursewareTop.setCreateDate(new Date());
            coursewareTop.setTop(1);
            coursewareTopMapper.insert(coursewareTop);
        } else {
            coursewareTop1.setTop(coursewareTop1.getTop() + 1);
            coursewareTopMapper.updateById(coursewareTop1);
        }
        //点击+1
        if (courseware.getTop() == null) {
            courseware.setTop(0);
        }
        courseware.setTop(courseware.getTop() + 1);
        coursewareMapper.updateById(courseware);
        return ResponseResult.errorResult(AppHttpCodeEnum.PQCG, AppHttpCodeEnum.PQCG.getErrorMessage());
    }


    @Override
    public ResponseResult Accountfind(AccountPage accountPage) {
        ArrayList<AccountList> arrayList = coursewareStudentMapper.accountfind(accountPage);
        return ResponseResult.okResult(arrayList);
    }

    @Override
    public ResponseResult findWeek(AccountPage accountPage) {
        UserStudent userStudent = userStudentMapper.selectById(accountPage.getId());
        int month = getMonth(userStudent.getCreateDate(), new Date());
        ArrayList<AccountWee> accountWees = ListCount(month);
        ArrayList<AccountList> arrayList = coursewareStudentMapper.findWeek(accountPage);
        if (arrayList.size() < 1) {
            ArrayList<Object> objects = new ArrayList<>();
            return ResponseResult.okResult(objects);
        }


        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        ArrayList<AccountListSho> accountListShos = new ArrayList<>();
        int i = 1;
        if (accountPage.getTime() == null) {
            for (AccountWee accountWee : accountWees) {
                AccountListSho accountListSho = new AccountListSho();
                ArrayList<AccountList> arrayList1 = new ArrayList<>();
                accountListSho.setId(i);
                accountListSho.setYear(accountWee.getYear());
                accountListSho.setMonth(accountWee.getXueDate());
                for (AccountList accountList : arrayList) {
                    if (sdf.format(accountWee.getXueDate()).equals(sdf.format(accountList.getXueDate()))) {
                        arrayList1.add(accountList);
                    }
                }
                ++i;
                accountListSho.setAccountLists(arrayList1);
                accountListShos.add(accountListSho);
            }
        } else {
            AccountListSho accountListSho = new AccountListSho();
            ArrayList<AccountList> arrayList1 = new ArrayList<>();
            for (AccountList accountList : arrayList) {
                accountListSho.setId(i);
                accountListSho.setYear(accountList.getXueDate());
                accountListSho.setMonth(accountList.getXueDate());
                arrayList1.add(accountList);
            }
            ++i;
            accountListSho.setAccountLists(arrayList1);
            accountListShos.add(accountListSho);

        }

        return ResponseResult.okResult(accountListShos);
    }

    @Override
    public ResponseResult downloadXia(Integer id) {
        Courseware courseware1 = coursewareMapper.selectById(id);
        courseware1.setDownload(courseware1.getDownload() + 1);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
    }


    @Override
    public ResponseResult WeekPeriod(AccountPage accountPage) {
//        ArrayList<AccountWee>    list = coursewareStudentMapper.acourWeek(accountPage);
        UserStudent userStudent = userStudentMapper.selectById(accountPage.getId());
        int month = getMonth(userStudent.getCreateDate(), new Date());
        ArrayList<AccountWee> accountWees = ListCount(month);
        ArrayList<AccountPeriod> arrayList = coursewareStudentMapper.findPeriod(accountPage);

        if (arrayList.size() < 1) {
            ArrayList<Object> objects = new ArrayList<>();
            return ResponseResult.okResult(objects);
        }
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        int i = 1;

        ArrayList<AccountPeriodList> accountListShos = new ArrayList<>();
        for (AccountWee accountWee : accountWees) {
            AccountPeriodList accountListSho = new AccountPeriodList();
            ArrayList<AccountPeriod> arrayList1 = new ArrayList<>();
            for (AccountPeriod accountList : arrayList) {
                accountListSho.setId(i);
                accountListSho.setYear(accountWee.getYear());
                accountListSho.setMonth(accountWee.getXueDate());
                if (sdf.format(accountWee.getXueDate()).equals(sdf.format(accountList.getLittleDate()))) {
                    accountList.setBigDate(dayList(accountList.getLittleDate()));//7天后的日期
                    if (accountList.getPattern() == 1) {
                        accountList.setName("教学周报");
                    } else if (accountList.getPattern() == 2) {
                        accountList.setName("评测周报");
                    }
                    arrayList1.add(accountList);
                }
            }
            ++i;
            accountListSho.setAccountLists(arrayList1);
            accountListShos.add(accountListSho);
        }

        return ResponseResult.okResult(accountListShos);
    }

    public ArrayList<AccountWee> ListCount(int month) {
        ArrayList<AccountWee> arrayList = new ArrayList<>();
        //获取当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("MM");

        Date today = new Date();
        String endDate = sdf.format(today); //当前日期
        //获取三十天前日期
        for (int i = 0; i <= month; i++) {
            AccountWee accountWee = new AccountWee();
            Calendar theCa = Calendar.getInstance();
            theCa.setTime(today);
            theCa.add(theCa.MONTH, -i); //月份
            Date start = theCa.getTime();
//            String startDate = sdf.format(start); //三十天之前日期
//            accountWee.setId(i);
            accountWee.setXueDate(start);
            accountWee.setYear(start);
            arrayList.add(accountWee);
        }
        return arrayList;
    }


    @Override
    public ResponseResult TearPeriod(AccountTeach accountPage) {
        ArrayList<AccountTeachList> accountTeachLists = coursewareStudentMapper.TearPeriod(accountPage);
        ArrayList<Integer> Coursecount = coursewareStudentMapper.CourseCount(accountPage);//课程数
        ArrayList<String> subjectcount = coursewareStudentMapper.SubjectCount(accountPage);//学科数
//        ArrayList<String>  =coursewareStudentMapper.SubjectCount(accountPage);//数学学科完成率

        for (AccountTeachList teachList : accountTeachLists) {
            Integer beyond = coursewareMapper.beyond(teachList.getHighest(), teachList.getCid());
            Integer zongdu = coursewareMapper.zongshu(teachList.getCid());
            teachList.setCourseCount(Coursecount.size());
            teachList.setSubjectCount(subjectcount.size());
            teachList.setLittleDate(accountPage.getLittleDate());
            teachList.setBigDate(accountPage.getBigDate());
            teachList.setAccuracy(beyond * 100 / zongdu);
            if (accountPage.getPattern() == 1) {
                teachList.setName("教学周报");
            } else if (accountPage.getPattern() == 2) {
                teachList.setName("评测周报");
            }
        }
        return ResponseResult.okResult(accountTeachLists);
    }


    /**
     * 获取两个日期相差几个月
     *
     * @param start
     * @param end
     * @return
     * @author
     * @date 2016-11-30 下午7:57:32
     */
    public static int getMonth(Date start, Date end) {
        if (start.after(end)) {
            Date t = start;
            start = end;
            end = t;
        }
        Calendar startCalendar = Calendar.getInstance();
        startCalendar.setTime(start);
        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTime(end);
        Calendar temp = Calendar.getInstance();
        temp.setTime(end);
        temp.add(Calendar.DATE, 1);

        int year = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
        int month = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);

        if ((startCalendar.get(Calendar.DATE) == 1) && (temp.get(Calendar.DATE) == 1)) {
            return year * 12 + month + 1;
        } else if ((startCalendar.get(Calendar.DATE) != 1) && (temp.get(Calendar.DATE) == 1)) {
            return year * 12 + month;
        } else if ((startCalendar.get(Calendar.DATE) == 1) && (temp.get(Calendar.DATE) != 1)) {
            return year * 12 + month;
        } else {
            return (year * 12 + month - 1) < 0 ? 0 : (year * 12 + month);
        }
    }


    @Override
    public ResponseResult Subjectshi(AccountTeach accountPage) {
        ArrayList<AccountSuject> accountSujects = coursewareStudentMapper.Subjectshi(accountPage);
        ArrayList<String> strings = new ArrayList<>();
        strings.add("物理");
        strings.add("化学");
        strings.add("生物");
        strings.add("数学");
//        accountSujects.remove(0);
        for (int i = 0; i < accountSujects.size(); i++) {
            if (accountSujects.get(i).getSubject().equals("null") || accountSujects.get(i).getSubject().equals(null)) {
                accountSujects.remove(i);
            }

        }

        boolean exit = false;
        for (int i = 0; i < strings.size(); i++) {
            exit = false;
            for (AccountSuject suject : accountSujects) {
                if (strings.get(i).equals(suject.getSubject())) {
                    exit = true;
                    break;
                }
            }
            if (!exit) {
                AccountSuject accountSuject = new AccountSuject();
                accountSuject.setSubject(strings.get(i));
                accountSuject.setTime(0);
                accountSujects.add(accountSuject);
            }
        }
        return ResponseResult.okResult(accountSujects);
    }


    @Override
    public ResponseResult TeachCount(AccountTeach accountPage) {

        ArrayList<HashMap<String, Object>> orders = coursewareStudentMapper.teachCount(accountPage);

        List<String> dayList = dayListCount(accountPage.getBigDate());
        boolean exists = false;
        for (int i = 0; i < dayList.size(); i++) {
            exists = false;
            for (Map<String, Object> hs : orders) {
                if (dayList.get(i).equals(hs.get("shoDate"))) {
                    exists = true;
                    break;
                }
            }
            if (!exists) {
                final String date2 = dayList.get(i);
                orders.add(i, new HashMap<String, Object>() {{
                    put("count", 0);
                    put("shoDate", date2);
                }});
            }
        }
        return ResponseResult.okResult(orders);

    }


    public List<String> dayListCount(Date today) {
        ArrayList<String> arrayList = new ArrayList<>();
        //获取当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
//        Date today = new Date();
        String endDate = sdf.format(today); //当前日期
        //获取三十天前日期
        for (int i = 6; i >= 1; i--) {
            Calendar theCa = Calendar.getInstance();
            theCa.setTime(today);
            theCa.add(theCa.DATE, -i); //最后一个数字30可改，30天的意思
            Date start = theCa.getTime();
            String startDate = sdf.format(start); //三十天之前日期
            arrayList.add(startDate);
        }
        return arrayList;
    }


    public Date dayList(Date today) {
//        ArrayList<String> arrayList = new ArrayList<>();
        //获取当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
//        Date today = new Date();
        String endDate = sdf.format(today); //当前日期
        //获取7天后日期

        Calendar theCa = Calendar.getInstance();
        theCa.setTime(today);
        theCa.add(theCa.DATE, +6); //最后一个数字7可改，7天的意思
        Date start = theCa.getTime();
//            String startDate = sdf.format(start); //三十天之后日期

        return start;
    }

    public ResponseResult CourseImg(MultipartFile file) {
        // 1. 对上传的图片进行校验: 这里简单校验后缀名
        // 另外可通过ImageIO读取图片的长宽来判断是否是图片,校验图片的大小等。
        this.ossClient = aliyunConfig.ossClient();
        if (file.getSize() >= 2097152) {
            return ResponseResult.okResult(508, "图片大于2MB");
        }


        // TODO 图片校验
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                isLegal = true;
                break;  // 只要与允许上传格式其中一个匹配就可以
            }
        }


        ResponseResult picUploadResult = new ResponseResult();
        // 格式错误, 返回与前端约定的error
        if (!isLegal) {
            picUploadResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR, AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR.getErrorMessage());
            return picUploadResult;
        }

        // 2. 准备上传API的参数
        String fileName = file.getOriginalFilename();
        String filePath = this.getFilePath(fileName);

        // 3. 上传至阿里OSS
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            picUploadResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, AppHttpCodeEnum.SERVER_ERROR.getErrorMessage());
            return picUploadResult;
        }

        // 上传成功
        picUploadResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());
        // 文件名(即直接访问的完整路径)
        Pian pian = new Pian();
        pian.setTime(new Date());
        pian.setUrl(aliyunConfig.getUrlPrefix() + filePath);
        return picUploadResult.ok(pian);
        // uid
//        picUploadResult.ok(String.valueOf(System.currentTimeMillis()));
//        return picUploadResult;
    }


    @Override
    public String[] uploadObject2OSS(OSSClient ossClient, File file, String bucketName, String folder, String format, String formats) {
        this.ossClient = aliyunConfig.ossClient();
        // 创建一个可重用固定线程数的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        String[] resultArr = new String[2];
        try {
            // 分片上传
            folder = folder + format;
            // 文件名
            String fileName = file.getName();
            // 文件扩展名
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));
            // 最终文件名：UUID + 文件扩展名
            fileName = formats + fileExtension;
            // 上传路径 如：appversion/20200723/a3662009-897c-43ea-a6d8-466ab8310c6b.apk
            // objectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg
            String objectName = folder + fileName;
//            log.info("上传到路径：" + objectName);
            // 文件大小
            long fileSize = file.length();
            // 创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            // 指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            // 指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            // 指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            // 如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(fileExtension));
            // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            // 创建InitiateMultipartUploadRequest对象
            InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName, metadata);
            // 初始化分片
            InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
            // 返回uploadId，它是分片上传事件的唯一标识，您可以根据这个uploadId发起相关的操作，如取消分片上传、查询分片上传等
            String uploadId = upresult.getUploadId();
            // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成
            List<PartETag> partETags = Collections.synchronizedList(new ArrayList<>());
            // 计算文件有多少个分片
            final long partSize = 1 * 1024 * 1024L; // 1MB
            long fileLength = file.length();
            int partCount = (int) (fileLength / partSize);
            if (fileLength % partSize != 0) {
                partCount++;
            }
            if (partCount > 10000) {
                throw new RuntimeException("分片总块数不能超过10000");
            } else {
//                log.info("分片总块数：" + partCount);
            }
            // 遍历分片上传
            for (int i = 0; i < partCount; i++) {
                long startPos = i * partSize;
                long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
                int partNumber = i + 1;
                // 实现并启动线程
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        InputStream inputStream = null;
                        try {
                            inputStream = new FileInputStream(file);
                            // 跳过已经上传的分片
                            inputStream.skip(startPos);
                            UploadPartRequest uploadPartRequest = new UploadPartRequest();
                            uploadPartRequest.setBucketName(bucketName);
                            uploadPartRequest.setKey(objectName);
                            uploadPartRequest.setUploadId(uploadId);
                            uploadPartRequest.setInputStream(inputStream);
                            // 设置分片大小。除了最后一个分片没有大小限制，其他的分片最小为100 KB。
                            uploadPartRequest.setPartSize(curPartSize);
                            // 设置分片号。每一个上传的分片都有一个分片号，取值范围是1~10000，如果超出这个范围，OSS将返回InvalidArgument的错误码。
                            uploadPartRequest.setPartNumber(partNumber);
                            // 每个分片不需要按顺序上传，甚至可以在不同客户端上传，OSS会按照分片号排序组成完整的文件。
                            UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
                            //每次上传分片之后，OSS的返回结果会包含一个PartETag。PartETag将被保存到PartETags中。
                            synchronized (partETags) {
                                partETags.add(uploadPartResult.getPartETag());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (inputStream != null) {
                                try {
                                    inputStream.close();
                                } catch (IOException e) {
//                                    log.error(e.getMessage());
                                }
                            }
                        }
                    }
                });
            }
            // 等待所有的分片完成
            // shutdown方法：通知各个任务（Runnable）的运行结束
            executorService.shutdown();
            while (!executorService.isTerminated()) {
                try {
                    // 指定的时间内所有的任务都结束的时候，返回true，反之返回false，返回false还有执行完的任务
                    executorService.awaitTermination(5, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
//                    log.error(e.getMessage());
                }
            }
            // 立即关闭所有执行中的线程
            // executorService.shutdownNow();

            // 验证是否所有的分片都完成
            if (partETags.size() != partCount) {
                throw new IllegalStateException("文件的某些部分上传失败！");
            } else {
//                log.info("文件上传成功：" + file.getName());
            }
            // 完成分片上传 进行排序。partETags必须按分片号升序排列
            Collections.sort(partETags, new Comparator<PartETag>() {
                @Override
                public int compare(PartETag o1, PartETag o2) {
                    return o1.getPartNumber() - o2.getPartNumber();
                }
            });
            // 创建CompleteMultipartUploadRequest对象
            // 在执行完成分片上传操作时，需要提供所有有效的partETags。OSS收到提交的partETags后，会逐一验证每个分片的有效性。当所有的数据分片验证通过后，OSS将把这些分片组合成一个完整的文件
            CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
            // 设置文件访问权限
            // completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.PublicRead);
            // 完成上传
            CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
            if (completeMultipartUploadResult != null) {
                // 解析结果
                resultArr[0] = completeMultipartUploadResult.getETag();
                resultArr[1] = objectName;
                return resultArr;
            }
        } catch (Exception e) {
            e.printStackTrace();
//            log.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        } finally {
            // 关闭OSSClient
//            ossClient.shutdown();
        }
        return null;
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileExtension 文件名扩展名
     * @return 文件的contentType
     */
    public static String getContentType(String fileExtension) {
        // 文件的后缀名
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".mp4".equalsIgnoreCase(fileExtension)) {
            return "video/mp4";
        }
        // android
        if (".apk".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.android.package-archive";
        }
        // ios
        if (".ipa".equals(fileExtension)) {
            return "application/vnd.iphone";
        }
        // 默认返回类型
        return "application/octet-stream";
    }

    @Override
    public ResponseResult Coursewarejian(MultipartFile file) {
        // 1. 对上传的图片进行校验: 这里简单校验后缀名
        // 另外可通过ImageIO读取图片的长宽来判断是否是图片,校验图片的大小等。

        this.ossClient = aliyunConfig.ossClient();
        if (file.getSize() > 2097152 * 250) {
            return ResponseResult.okResult(508, "文件大于500MB");
        }
        // TODO 图片校验
        boolean isLegal = true;
        String type = ".apk";
        if (!StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
            isLegal = false;
        }


        ResponseResult picUploadResult = new ResponseResult();
        // 格式错误, 返回与前端约定的error
        if (!isLegal) {
            return picUploadResult.errorResult(AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR, AppHttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR.getErrorMessage());
        }

        // 2. 准备上传API的参数
        String fileName = file.getOriginalFilename();
        String filePath = this.getFileWenPath(fileName);

        // 3. 上传至阿里OSS
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            // 上传失败
            picUploadResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, AppHttpCodeEnum.SERVER_ERROR.getErrorMessage());
            return picUploadResult;
        }

        // 上传成功
        picUploadResult.errorResult(AppHttpCodeEnum.SUCCESS, AppHttpCodeEnum.SUCCESS.getErrorMessage());


        // 文件名(即直接访问的完整路径)
        Pian pian = new Pian();
        pian.setName(fileName);
        Long size = file.getSize();
        pian.setCapacity(size.intValue());
        pian.setUrl(aliyunConfig.getUrlPrefix() + filePath);
        pian.setTime(new Date());
        File file1 = null;
        try {
            file1 = multipartFileToFile(file);
            try {
                pian.setMd5(MD5Utils.getMD5(file1));
                MultipartFileToFileUtil.deleteTempFile(file1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        picUploadResult.ok(pian);
        return picUploadResult;
    }

    /**
     * 将 multipartFile 转换成  临时 file 文件.（该临时文件使用完记得 delete掉.）
     *
     * @param multipartFile multipartFile
     * @return 临时的 file 文件.
     * @throws IOException io
     */
    public static File multipartFileToFile(MultipartFile multipartFile) throws IOException {
        if (multipartFile == null) {
            return null;
        }

        InputStream inputStream = multipartFile.getInputStream();

        File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();

        //单个文件最大
        factory.setMaxFileSize("500MB"); //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("500MB");
        return factory.createMultipartConfig();
    }

    /**
     * 上传的目录
     * 目录: 根据年月日归档
     * 文件名: 时间戳 + 随机数
     *
     * @param fileName
     * @return
     */
    private String getFilePath(String fileName) {
        return "kejian/" + System.currentTimeMillis() + "." + StringUtils.substringAfterLast(fileName, ".");
    }

    private String getFileWenPath(String fileName) {
        return "keApk/" + fileName;
    }

    private String getFilerenewalPath(String fileName) {
        return "keBan/" + fileName;
    }


}
